package com.mihe.gateway.filter;

import cn.hutool.core.util.ReUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mihe.core.constant.RedisKeyConstant;
import com.mihe.core.constant.RequestConstant;
import com.mihe.gateway.config.JwtConfig;
import com.mihe.gateway.result.ExceptionResult;
import com.mihe.jwt.util.JwtUtil;
import com.mihe.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author Administrator
 */
@Component
public class TokenVerifyFilter implements GlobalFilter, Ordered {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private RedisService redisService;

    private static final String START_TIME = "startTime";

    public TokenVerifyFilter() {
        log.info("Loaded GlobalFilter [Logging]");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = TraceContext.traceId();

        String info = String.format("traceId is {%s},Method:{%s} Host:{%s} Path:{%s} Query:{%s}",
                traceId,
                exchange.getRequest().getMethod().name(),
                exchange.getRequest().getURI().getHost(),
                exchange.getRequest().getURI().getPath(),
                exchange.getRequest().getQueryParams());

        log.info(info);
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());

        String url = exchange.getRequest().getURI().getPath();
        String[] ignoreUrls = jwtConfig.getIgnoreUrls();
        if (hasAuth(ignoreUrls, url)|| ReUtil.isMatch(IgnoreFilter.RegExp,url)) {
            return chain.filter(exchange);
        }
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        ServerHttpResponse serverHttpResponse = exchange.getResponse();

        if (StringUtils.isBlank(token)) {
            return authErro(serverHttpResponse, "请登录");
        } else {
            try {
                DecodedJWT verify = JwtUtil.verifyToken(token);
                long uid = verify.getClaim(RequestConstant.ADMIN_ID).asLong();
                String userName = verify.getClaim(RequestConstant.ADMIN_NAME).asString();
                String finalUserName = URLEncoder.encode(userName, "utf8");

                String key = RedisKeyConstant.USER_TOKEN_KEY + uid;
                Object val = redisService.getCacheObject(key);

                if (val == null) {
                    return authErro(serverHttpResponse, "token已经过期");
                }

                Consumer<HttpHeaders> httpHeaders = httpHeader -> {
                    httpHeader.set(RequestConstant.ADMIN_ID, String.valueOf(uid));
                    httpHeader.set(RequestConstant.ADMIN_NAME, finalUserName);
                };
                ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
                ServerWebExchange serverWebExchange = exchange.mutate().request(serverHttpRequest).build();

                return chain.filter(serverWebExchange);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return authErro(serverHttpResponse, "认证失败");
            }
        }
    }

    /**
     * 认证错误输出
     *
     * @param resp 响应对象
     * @param mess 错误信息
     * @return
     */
    private Mono<Void> authErro(ServerHttpResponse resp, String mess) {
        //resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ExceptionResult responseResult = new ExceptionResult(401, mess);

        String returnStr = "";
        try {
            returnStr = objectMapper.writeValueAsString(responseResult);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer buffer = resp.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }


    private boolean hasAuth(String[] uris, String url) {
        List<String> uriList = Arrays.asList(uris);
        url = url.substring(url.indexOf("/", 1));
      /*  if (uriList.contains(url)) {
            return true;
        }*/

        for(String uri :uriList){
            if (url.contains(uri)) {
                return true;
            }
        }
        url = url.substring(1);
        if (url.startsWith("swagger") || url.startsWith("webjars") || url.startsWith("v2")) {
            return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
